package br.com.ss.portal.controller.eleitor;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import br.com.ss.portal.component.Message;
import br.com.ss.portal.component.Util;
import br.com.ss.portal.exceptions.EleitorValidator;
import br.com.ss.portal.exceptions.ValidationException;
import br.com.ss.portal.model.entity.Eleitor;
import br.com.ss.portal.model.entity.Responsavel;

@Controller
@Scope("session")
public class EleitorController {

	private Eleitor eleitor;
	private Eleitor selected;
	private Responsavel responsavel;
	private List<Eleitor> eleitores;
	private List<Responsavel> responsaveis;

	@Autowired
	private IEleitorService services;

	@PostConstruct
	public void init() {
		this.responsaveis = services.listResponsavel();
		this.eleitores = services.Buscartodos();
		this.eleitor = new Eleitor();
		this.responsavel = new Responsavel();
	}

	public void salvar() {
		try {
			EleitorValidator.validarCampos(this.eleitor);

			this.eleitor.setCelular(Util.removeMask(eleitor.getCelular()));
			this.eleitor.setResidencial(Util.removeMask(eleitor
					.getResidencial()));
			this.eleitor.setComercial(Util.removeMask(eleitor.getComercial()));

			this.eleitor = this.eleitor.removeMask(eleitor);

			this.eleitor.setResponsavel(this.responsavel);

			services.salvar(this.eleitor);
			setEleitores(services.Buscartodos());

			this.eleitor = new Eleitor();

			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_INFO, Message.INFO,
							Message.INFO_MESSAGE));

		} catch (ValidationException e) {
			e.getMessage();
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_WARN, "Warnning", e
							.getMessage()));
		} catch (Exception e) {
			System.out.println(" e.getMessage() == " + e.getMessage());
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro", e
							.getMessage()));
		}
	}

	public void deletar() {
		services.deletar(this.selected);
		getEleitores();
		Iniciar();
	}

	public void editar() {
		this.eleitor = this.selected;
		this.responsavel = this.selected.getResponsavel();
		System.out.println(this.responsavel.toString());

	}

	public void cancelar() {
		Iniciar();
	}

	private void Iniciar() {
		this.eleitor = new Eleitor();
	}

	public List<Responsavel> getResponsaveis() {
		return responsaveis;
	}

	public void setResponsaveis(List<Responsavel> responsaveis) {
		this.responsaveis = responsaveis;
	}

	public Responsavel getResponsavel() {
		return responsavel;
	}

	public void setResponsavel(Responsavel responsavel) {
		this.responsavel = responsavel;
	}

	public Eleitor getEleitor() {
		return eleitor;
	}

	public void setEleitor(Eleitor eleitor) {
		this.eleitor = eleitor;
	}

	public void setEleitores(List<Eleitor> eleitores) {
		this.eleitores = eleitores;
	}

	public List<Eleitor> getEleitores() {
		this.eleitores = services.Buscartodos();
		return this.eleitores;
	}

	public List<Eleitor> getEleitoresPorId() {

		System.out.println("Entrou no getEleitores");
		System.out.println(selected.toString());
		this.eleitores = services.Buscartodos();
		return this.eleitores;
	}

	public void setSelected(Eleitor selected) {
		this.selected = selected;
	}

	public Eleitor getSelected() {
		return selected;
	}

	@SuppressWarnings("deprecation")
	public String createPdfReport() {
		try {

			Map<String, Object> params = new HashMap<String, Object>();

			FacesContext facesContext = FacesContext.getCurrentInstance();

			ServletContext servletContext = (ServletContext) facesContext
					.getExternalContext().getContext();

			String reportUrlReal = servletContext
					.getRealPath("/pages/eleitor/listagemEleitor.jasper");

			JasperPrint jasperPrint = JasperFillManager.fillReport(
					reportUrlReal, params, new JRBeanCollectionDataSource(
							this.eleitores));

			HttpServletResponse response = (HttpServletResponse) facesContext
					.getExternalContext().getResponse();

			ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();
			JasperExportManager.exportReportToPdfStream(jasperPrint, pdfStream);

			response.setContentType("application/pdf");
			response.setHeader("Content-Disposition",
					"attachment; filename= RelatorioEleitores.pdf");
			response.setContentLength(pdfStream.size());

			ServletOutputStream flusher;
			flusher = response.getOutputStream();
			pdfStream.writeTo(flusher);
			flusher.flush();
			flusher.close();
			FacesContext.getCurrentInstance().responseComplete();
			pdfStream.close();
			pdfStream = null;

			return "";

		} catch (JRException e) {
			e.printStackTrace();
			return "";
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

	}

	@SuppressWarnings("deprecation")
	public void imprimir() throws IOException, JRException {
		ByteArrayOutputStream byteOutPutStream = new ByteArrayOutputStream();

		try {
			FacesContext facesContext = FacesContext.getCurrentInstance();

			HttpServletResponse response = (HttpServletResponse) facesContext
					.getExternalContext().getResponse();

			ServletContext servletContext = (ServletContext) facesContext
					.getExternalContext().getContext();

			String reportUrlReal = servletContext
					.getRealPath("/pages/eleitor/listagemEleitor.jasper");

			JasperPrint preencher = JasperFillManager.fillReport(reportUrlReal,
					null, new JRBeanCollectionDataSource(this.eleitores));

			System.out.println("Writing to InPut stream...");
			JasperExportManager.exportReportToPdfStream(preencher,
					byteOutPutStream);

			System.out.println("Size of OutPut: " + byteOutPutStream.size());
			response.setContentLength(byteOutPutStream.size());
			response.setContentType("application/pdf");
			// response.setHeader("Content-Disposition","attachment; filename=wpinvenotry-"
			// + new Date() + ".pdf");
			// response.setHeader("Cache-Control", "no-cache");

			System.out.println("Writing to OutPut stream...");
			ServletOutputStream servletOutPutStream = response
					.getOutputStream();
			servletOutPutStream.write(byteOutPutStream.toByteArray(), 0,
					byteOutPutStream.size());

			System.out.println("Closing stream...");
			servletOutPutStream.flush();
			servletOutPutStream.close();

			FacesContext.getCurrentInstance().responseComplete();

		} catch (JRException jrex) {
			jrex.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
